var request = require('request');
var fs = require('fs');
const path = require('path')

/*
* url 网络文件地址
* filename 文件名
* callback 回调函数
*/
function downloadFile(uri, filePath, callback){
    // console.log('download uri: ', uri)
    const _name = filePath.split('/')[1]
    // 读取tempTsDir目录下有没有当前的fileName，如果有就直接执行cb
    const tsList = fs.readdirSync(path.join(__dirname, 'tempTsDir'))
    if (tsList.includes(_name)) {
        callback()
        return
    }
    const writeStream = fs.createWriteStream(filePath);
    const readStream = request(uri)
    readStream.pipe(writeStream).on('close', callback)
    readStream.on('error', () => {
        console.log('downloadFile err')
        downloadFile(uri, filePath, callback)
    })
    writeStream.on('error', () => {
        console.log('downloadFile err')
        downloadFile(uri, filePath, callback)
    })
}

module.exports = downloadFile